

#import "ShopMenuController.h"
#import "DishManager.h"
#import "Dish.h"
#import "Constants.h"

@implementation ShopMenuController
@synthesize styleOfCookingList;
@synthesize dishCategories;
@synthesize currentDishCategory;
@synthesize leftTable;
@synthesize rightTable;
@synthesize isTouched;
@synthesize phoneAry;
@synthesize filePath5;
@synthesize filePath6;
@synthesize filePath7;

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"ShopMenuController内存不够");
}

//加载指示器
-(void)showHUD{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	[self.navigationController.view addSubview:HUD];
	HUD.dimBackground = YES;
    HUD.delegate = self;
    [HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

- (void)myTask {
    phoneAry=[recieveDictionary objectForKey:@"phoneArray"];
//    leftTable = [[[UITableView alloc] initWithFrame:CGRectMake(0, 25, 90, 342)] autorelease];
//    //设置cell为无边框
//    leftTable.separatorStyle = UITableViewCellSeparatorStyleNone;   
//    //设置滚动条的位置
//    leftTable.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, leftTable.bounds.size.width-7);
//    leftTable.delegate = self;
//    leftTable.dataSource = self;
//    leftTable.tag = 1;
//    //减慢tableview的滚动速度，正常值为1.f
//    leftTable.decelerationRate=0.5f;
//
//    rightTable = [[[UITableView alloc] initWithFrame:CGRectMake(90, 25, 230, 342)] autorelease]; 
//    rightTable.hidden=YES;
//    rightTable.delegate = self;
//    rightTable.dataSource = self;
//    //设置不显示滚动条
//    rightTable.showsVerticalScrollIndicator=YES;
//    rightTable.tag = 2;
//    //减慢tableview的滚动速度，正常值为1.f
//    rightTable.decelerationRate=0.5f;
//    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"leftPanelBg" ofType:@"png"];
//    UIImageView *bgView = [[[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath]] autorelease];
//    [leftTable setBackgroundView:bgView];
////    [bgView release];
//    [self.view addSubview:leftTable];
//    [self.view addSubview:rightTable];
    
    //从后台获取所需的数据
    DishManager *manager = [[DishManager alloc] init];
    dishCategories = [manager getAllDishesBySupId:(NSString *)[recieveDictionary objectForKey:@"supId"]];
//    fmdbDishManager=[[FMDBDishManager alloc]init];
//    appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;	
//    if([appDelegate status])
//    {
        //联网，添加到本地
//        dishCategories = [manager getAllDishesBySupId:(NSString *)[recieveDictionary objectForKey:@"supId"]];
//        //插入本地
//        NSInteger supid=[[recieveDictionary objectForKey:@"supId"]intValue];
//        [fmdbDishManager insertAllDishesBySupIdToLoc:dishCategories supplierid:supid];
//    }
//    else{
//        dishCategories=[fmdbDishManager getAllDishesBySupIdFromLoc:[recieveDictionary objectForKey:@"supId"]];
//    }
//    [fmdbDishManager release];

    //设置页面所要显示的数据信息
    if([dishCategories count]==0)
    {
        currentDishCategory=Nil;   
    }
    else
    {
        currentDishCategory = (DishCategory *)[dishCategories objectAtIndex:0];
    }
    self.styleOfCookingList = dishCategories;
    
    
    
    //设置价格
    
//    Dish *dish =  [currentDishCategory.dishes objectAtIndex:row];
    
    
//    [manager release];
    [leftTable reloadData];
    leftTable.hidden=NO;
    //默认选中左侧第一个
    NSIndexPath *first = [NSIndexPath indexPathForRow:0 inSection:0];
    //当没有菜单的时候不会闪退
    if([dishCategories count]!=0)
    {
        [leftTable selectRowAtIndexPath:first animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
    [rightTable reloadData];
    rightTable.hidden=NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //添加手势
    //后退
    UISwipeGestureRecognizer *recognizer; 
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
    [[self view] addGestureRecognizer:recognizer];
    //打电话
    recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
    [[self view] addGestureRecognizer:recognizer];
    self.navigationController.navigationBarHidden = NO; 
    //设置视图title
    self.title= [recieveDictionary objectForKey:@"supName"];
    //设置返回上一页按钮
    //第一个参数为按钮标题
    //第二个参数是按钮样式
    //第三个参数接受消息的对象
    //第四个参数是按钮的回调函数
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,54,27)];
    NSString *filePath=[[NSBundle mainBundle] pathForResource:@"navLeftBtn" ofType:@"png"];
    [leftButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath] forState:UIControlStateNormal];
    [leftButton setTitle:@"返 回" forState:UIControlStateNormal];
    leftButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
    [leftButton addTarget:self action:@selector(backButtonPressdDelay) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    //设置为左边按钮
    [[self navigationItem] setLeftBarButtonItem:leftItem];
    
    //定义导航栏右侧按钮
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0,0,54,27)];
    NSString *filePath2=[[NSBundle mainBundle] pathForResource:@"navRightBtn" ofType:@"png"];
    [rightButton setBackgroundImage:[UIImage imageWithContentsOfFile:filePath2] forState:UIControlStateNormal];
    [rightButton setTitle:@"电 话" forState:UIControlStateNormal];
    rightButton.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:14]; 
    [rightButton addTarget:self action:@selector(phoneCall) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    //设置为右边按钮
    [[self navigationItem] setRightBarButtonItem:rightItem];

    NSString *filePath4=[[NSBundle mainBundle] pathForResource:@"topBg" ofType:@"png"];
    UIImageView *topView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath4]];
    [topView setFrame:CGRectMake(0, -5, 320, 30)];
    [self.view addSubview:topView];    
    
    leftTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 25, 90, 342)];
    //设置cell为无边框
    leftTable.separatorStyle = UITableViewCellSeparatorStyleNone;   
    //设置滚动条的位置
    leftTable.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, leftTable.bounds.size.width-7);
    leftTable.delegate = self;
    leftTable.dataSource = self;
    leftTable.tag = 1;
    //减慢tableview的滚动速度，正常值为1.f
    leftTable.decelerationRate=0.5f;
    
    rightTable = [[UITableView alloc] initWithFrame:CGRectMake(90, 25, 230, 342)]; 
    rightTable.hidden=YES;
    rightTable.delegate = self;
    rightTable.dataSource = self;
    //设置不显示滚动条
    rightTable.showsVerticalScrollIndicator=YES;
    rightTable.tag = 2;
    //减慢tableview的滚动速度，正常值为1.f
    rightTable.decelerationRate=0.5f;
    NSString *filePath8=[[NSBundle mainBundle] pathForResource:@"leftPanelBg" ofType:@"png"];
    UIImageView *bgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath8]];
    [leftTable setBackgroundView:bgView];
    [self.view addSubview:leftTable];
    [self.view addSubview:rightTable];

    
    
    filePath5=[[NSBundle mainBundle] pathForResource:@"defaultBg" ofType:@"png"];
    filePath6=[[NSBundle mainBundle] pathForResource:@"touchBg" ofType:@"png"];
    filePath7=[[NSBundle mainBundle] pathForResource:@"selectBg" ofType:@"png"];
    
    [self showHUD];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:NO];
    isTouched=YES;
}

- (void)backButtonPressdDelay{
    if(isTouched){
        isTouched=NO;
        
        NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
        SystemSoundID system_sound_id;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
        AudioServicesPlaySystemSound(system_sound_id);
        
        [self performSelector:@selector(backButtonPressd) withObject:NULL afterDelay:0.1];
}
}



- (void)backButtonPressd{
    //将当前视图推出栈，程序将进入上一视图
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)phoneCall{
    NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
    SystemSoundID system_sound_id;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
    AudioServicesPlaySystemSound(system_sound_id);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"拨打电话" message:@"请选择要拨打的号码" delegate:self cancelButtonTitle:@"取  消" otherButtonTitles:nil];
    for(NSString *phone in phoneAry){
        [alert addButtonWithTitle:phone];
    }
    alert.tag = 1;
	[alert show];
}

//根据被点击按钮的索引处理点击事件  
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  
    //tag为1时为点击拨号按钮时弹出的对话框
    if(alertView.tag == 1){
        NSString *number = [alertView buttonTitleAtIndex:buttonIndex];
        //phoneNumber为号码字符串 
        NSString *phoneNumber = [[NSString alloc] initWithFormat:@"tel://%@",number]; 
        //拨号 
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]]; 
    }
}

//手势
-(void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    //后退
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    //打电话
    if(recognizer.direction==UISwipeGestureRecognizerDirectionLeft) {
        [self phoneCall];
    }
}



//- (void)rootButtonPressd{
//    //直接进入根视图
//    [self.navigationController popToRootViewControllerAnimated:YES];
//}




//返回表试图分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView.tag==1){
        return [dishCategories count];
    }else{
        return [currentDishCategory.dishes count];
    }
    [self viewDidLoad];
}

//滚动的过程无法点击左侧菜品类型按钮
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    leftTable.allowsSelection=NO;
}
//滚动结束后可以点击
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    leftTable.allowsSelection=YES;
}


//设置表试图每行显示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag == 1)
    {
        static NSString *identifier = @"TypeIdentifier";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];
        if(cell==nil){
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        NSUInteger row = [indexPath row];
        DishCategory *dishCategory = (DishCategory *)[styleOfCookingList objectAtIndex:row];
        cell.textLabel.text = dishCategory.dishCategoryName;
        cell.textLabel.font = [UIFont boldSystemFontOfSize:15];

        cell.textLabel.textAlignment = UITextAlignmentCenter;
        
        [cell setTag:dishCategory.dishCategoryId];
        
        
        

        UIImageView *defaultBgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath5]];

        UIImageView *touchBgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath6]];

        UIImageView *selectBgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:filePath7]];
        
        [cell setBackgroundView:defaultBgView];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectedBackgroundView = touchBgView;
        cell.editingAccessoryView = selectBgView;
        return cell;
    }
    else
    {
        static NSString *CellIdentifier = @"DishCellIdentifier";
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }else {
            RemoveAllSubViews(cell.contentView);
        }
        
        NSInteger row = [indexPath row];
        Dish *dish =  [currentDishCategory.dishes objectAtIndex:row];
        UILabel *nameLabel = (UILabel *)[cell.contentView viewWithTag:100];
        if (nameLabel == nil) {
            nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 200, 14)];
            nameLabel.opaque=YES;
            [nameLabel setText:dish.dishName];
            [nameLabel setFont:[UIFont boldSystemFontOfSize:14]];
            nameLabel.tag = 100;
            [cell.contentView addSubview:nameLabel];
        }

        
        
        
        UILabel *priceLabel = (UILabel *)[cell.contentView viewWithTag:200];
        if (priceLabel == nil) {
            priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 25, 210, 12)];
            priceLabel.opaque=YES;
            //如果价格为0，显示备注
            if (dish.price==0) {
                NSString *priceToStr=[[NSString alloc]initWithFormat:@"%@",dish.desc];
                [priceLabel setText:priceToStr];
            }
            else{
                if(dish.secondPrice == 0){
                    NSString *priceToStr=[[NSString alloc]initWithFormat:@"¥ %0.2f",dish.price];
                    [priceLabel setText:priceToStr];
                }
                else{
                    NSString *priceToStr=[[NSString alloc]initWithFormat:@"小:¥ %0.2f",dish.price];
                     [priceLabel setText:priceToStr];
                }
            }
            [priceLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
            [priceLabel setFont:[UIFont boldSystemFontOfSize:12]];
            priceLabel.tag = 200;
            [cell.contentView addSubview:priceLabel];
        }
        
        if (dish.secondPrice != 0 && dish.secondPrice != PRICE_BY_TIME) {
            UILabel *secondPriceLabel = (UILabel *)[cell.contentView viewWithTag:201];
            if (secondPriceLabel == nil) {
                secondPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(85, 25, 80, 12)];
                secondPriceLabel.opaque=YES;
                NSString *priceToStr=[[NSString alloc]initWithFormat:@"中:¥ %0.2f",dish.secondPrice];
                [secondPriceLabel setText:priceToStr];
                [secondPriceLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
                [secondPriceLabel setFont:[UIFont boldSystemFontOfSize:12]];
                secondPriceLabel.tag = 201;
                [cell.contentView addSubview:secondPriceLabel];
            }
        }
        
        if (dish.thirdPrice != 0 && dish.thirdPrice != PRICE_BY_TIME) {
            UILabel *thirdPriceLabel = (UILabel *)[cell.contentView viewWithTag:202];
            if (thirdPriceLabel == nil) {
                thirdPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(155, 25, 80, 12)];
                thirdPriceLabel.opaque=YES;
                NSString *priceToStr=[[NSString alloc]initWithFormat:@"大:¥ %0.2f",dish.secondPrice];                
                [thirdPriceLabel setText:priceToStr];
                [thirdPriceLabel setTextColor:[UIColor colorWithRed:255.0/255.0 green:111.0/255.0 blue:6.0/255.0 alpha:1.0f]];
                [thirdPriceLabel setFont:[UIFont boldSystemFontOfSize:12]];
                thirdPriceLabel.tag = 202;
                [cell.contentView addSubview:thirdPriceLabel];
            }
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        cell.tag = dish.dishId;
        return cell;
    }
}

//设置表试图行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath   
{
    if(tableView.tag==1){
        return 50;
    }else{
        return 45;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView.tag == 1){
        NSURL *system_sound_url=[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1248" ofType:@"wav"]];
        SystemSoundID system_sound_id;
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)system_sound_url, &system_sound_id);
        AudioServicesPlaySystemSound(system_sound_id);
        
        NSInteger row = [indexPath row];
        currentDishCategory = (DishCategory *)[dishCategories objectAtIndex:row];
//        [self performSelector:@selector(reloadData) withObject:NULL afterDelay:0.1];
[self performSelectorOnMainThread:@selector(onResponseInMainThread) withObject:nil waitUntilDone:YES];
    }
}
-(void)reloadData{
//    [self performSelectorOnMainThread:@selector(onResponseInMainThread) withObject:nil waitUntilDone:YES];


}
-(void)onResponseInMainThread{

    [rightTable scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO]; 
    leftTable.allowsSelection=YES;
    [rightTable reloadData];
}


- (void)viewDidUnload
{
    self.styleOfCookingList=nil;
self.dishCategories=nil;
    self.currentDishCategory=nil;
self.leftTable=nil;
    self.rightTable=nil;
    self.phoneAry=nil;
self.filePath5=nil;
    self.filePath6=nil;
self.filePath7=nil;
    [super viewDidUnload];
}

//- (void)dealloc {
//
//}
@end
